package jwt

import (
	"ginblog/model/interfaces"
	"ginblog/utils"
	"ginblog/utils/errmsg"
	"github.com/dgrijalva/jwt-go/v4"
	"github.com/gin-gonic/gin"
	"time"
)

type JwtKey struct {
	JwtKey []byte
}

type MyClaims struct {
	Username string `json:"username"`
	Id       uint   `json:"id"`
	jwt.StandardClaims
}

// getJwtKey / 获取JwtKey对象
func getJwtKey() *JwtKey {
	return &JwtKey{
		[]byte(utils.JwtKey),
	}
}

// CreateToken /根据JwtKey生成token
func (j *JwtKey) CreateToken(claims MyClaims) (string, error) {
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	return token.SignedString(j.JwtKey)
}

// SetToken /获取并设置Token
func SetToken(c *gin.Context, Login interfaces.ILogin) (bool, string) {
	jwtKey := getJwtKey()
	claims := MyClaims{
		Id:       Login.GetUserId(),
		Username: Login.GetUserName(),
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: jwt.At(time.Now().Add(time.Hour * 2)),
			Issuer:    "GinBlog",
		},
	}
	token, err := jwtKey.CreateToken(claims)

	if err != nil {
		return false, ""
	}
	return true, token
}

// ParserToken 解析token
func ParserToken(tokenString string) (int, *MyClaims) {
	jwtKey := getJwtKey()
	token, err := jwt.ParseWithClaims(tokenString, &MyClaims{}, func(token *jwt.Token) (interface{}, error) {
		return jwtKey.JwtKey, nil
	})

	if err != nil {

	}

	if token != nil {
		if claims, ok := token.Claims.(*MyClaims); ok && token.Valid {
			return 0, claims
		}
		return errmsg.ERROR_TOKEN_RUNTIME, nil
	}
	return errmsg.ERROR_TOKEN_RUNTIME, nil
}
